package com.xyz.interceptor;

import com.free.ext.logger.FreeLogger;
import com.free.ext.logger.FreeLoggerFactory;
import com.xyz.domain.constants.EhCacheConstants;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;

@Aspect
@Component
public class CacheUsedInterceptor {

    private static final FreeLogger LOGGER = FreeLoggerFactory.getLogger(CacheUsedInterceptor.class);

    @Autowired
    protected EhCacheCacheManager ehCacheCacheManager;

//    @Pointcut("@annotation(com.xyz.interceptor.QueueCacheInfo)")
//    public void warpperPoint() {
//
//    }

    @Around("@annotation(queueCacheInfo)")
    public Object around(ProceedingJoinPoint point, QueueCacheInfo queueCacheInfo) throws Throwable {

        String formarString = queueCacheInfo.smsFormart();
        String phone = point.getArgs()[0].toString();
        String phoneSmsCacheCode = String.format(formarString,phone);

        LOGGER.info("SMS手机号放入OneQueueCode，{}代码，开始", phoneSmsCacheCode);
        Object res = null;
        try {
            Cache.ValueWrapper valueWrapper =  ehCacheCacheManager.getCache(EhCacheConstants.OneTimeQueue).putIfAbsent(phoneSmsCacheCode,"1");
            if(valueWrapper == null || valueWrapper.get() == null){
                res = ((ProceedingJoinPoint) point).proceed();
                ehCacheCacheManager.getCache(EhCacheConstants.OneTimeQueue).evict(phoneSmsCacheCode);
            }else{
                LOGGER.info("SMS手机号放入OneQueueCode，{}代码连续发送直接关闭，结束", phoneSmsCacheCode);
            }
        } catch (Throwable t) {
            ehCacheCacheManager.getCache(EhCacheConstants.OneTimeQueue).evict(phoneSmsCacheCode);
            LOGGER.info("SMS手机号放入OneQueueCode，{}代码，调用方法{}({})发生异常:{}",phoneSmsCacheCode, point.getSignature(), params(point.getArgs()), t.getMessage());
            throw t;
        }
        LOGGER.info("SMS手机号放入OneQueueCode，{}代码，结束", phoneSmsCacheCode);
        return res;
    }

    private String params(Object[] params)
    {
        StringBuilder strBuilder = new StringBuilder();
        Arrays.asList(params).forEach(x -> {
            if (x == null)
            {
                strBuilder.append("null");
            }
            else
            {
                strBuilder.append(((Object) x).toString());
            }
        });
        return strBuilder.toString();
    }

}